#include <REGX52.H>
#include "Delay.h"
#include "Timer1.h"
#include "IR.h"
#include "TimeShow.h"
#include "DS1302.h"
#include "oled.h"
#include "Key.h"
//#include "MatrixKey.h"
sbit Motor = P1^0;


unsigned char Command,KeyNum,MODE,Key_T;
unsigned char Counter ,Compare;

unsigned char IR_GetState()
{
//	unsigned char Command;
	unsigned char IR_keyNumber=0;
		if(IR_GetDataFlag())
		{
			Command=IR_GetCommand();
			if(Command == IR_MODE){IR_keyNumber = 1;}//模式改变
			if(Command == IR_NEXT){IR_keyNumber = 2;}//光标后移
			if(Command == IR_PREVIOUS){IR_keyNumber = 3;}//光标前移
			if(Command == IR_VOL_ADD){IR_keyNumber = 4;}//值加
			if(Command == IR_VOL_MINUS){IR_keyNumber = 5;}//值减
			if(Command == IR_MUTE	){IR_keyNumber = 6;}//关闭闹钟
			if(Command == IR_EQ	){IR_keyNumber = 7;}//确认修改时间
			if(Command == IR_POWER	){IR_keyNumber = 8;}//关闭闹钟和温度报警
		}
		return IR_keyNumber;
}

unsigned char IR_Key()
{
	unsigned char Temp=0;
	Temp = IR_GetState();
	return Temp;
}

void SetMODE(unsigned char i)
{
	if(i==1)
	{
		MODE=0;
	}
}

void main(){
	
	IR_Init();
	Timer1_Init();
	oled_init();
	oled_clear();
  DS1302_Init();
	DS1302_SetTime();
	while (1)
	{
		Compare=100;
		SetMODE(GetMODE0());
		KeyNum = IR_Key();
		if(KeyNum==0)
		{
			KeyNum = Key();
		}
			//闹钟响铃
			Clock_Ring(KeyNum);	
			//按键1进行模式选择,以及模式功能
			if(KeyNum==1)
			{
				if(MODE==0){MODE=1;}
				else if(MODE==1){MODE=2;oled_clear();TimeSetSelect0();}
				else if(MODE==2){MODE=3;}
				else if(MODE==3){MODE=0;oled_clear();TimeSetSelect0();}
			}
			OLED_ShowNum(120,6,MODE,1,8);
			switch(MODE)
			{
				case 0: DS1302_ReadTime();TimeShow();break;
				case 1: TimeSet(KeyNum);break;
				case 2: Clock_Show();break;
				case 3: Clock_Set(KeyNum);break;
			}
	}

}


//定时器
void Timer1_Routine() interrupt 3
{		
		static unsigned int T1Count1,T1Count2;
		TL1 = 0x9C;		//设置定时初始值
		TH1 = 0xFF;		//设置定时初始值
		T1Count1++;
		if(T1Count1 >= 500){
			T1Count1=0;
			TimeSetFlash();
		}
		T1Count2++;
		if(T1Count2 >= 200){
				T1Count2=0;
				Key_Loop();
		}
//		Counter++;
//		Counter%=100;
//		if(Counter<Compare)
//		{
//			Motor=1;
//		}
//		else
//		{
//			Motor=0;
//		}
		
}